package maosy.oauth2.password.controller

import maosy.oauth2.password.entities.TbUserEntity
import maosy.oauth2.password.exception.DataNotFoundException
import maosy.oauth2.password.exception.TokenInvalidException
import maosy.oauth2.password.oto.TBUserOTO
import maosy.oauth2.password.ro.CreateUserRO
import maosy.oauth2.password.service.UserService
import maosy.oauth2.password.vo.TBUserEntityVO
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.security.core.Authentication
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices
import org.springframework.web.bind.annotation.*
import java.io.Serializable
import java.security.Principal
import javax.annotation.Resource

@RestController
@RequestMapping("api/user")
open class UserController {

    @Autowired
    private lateinit var userSrv: UserService
    @Resource
    private lateinit var tokenSrv: ConsumerTokenServices

    @GetMapping("logout/{token}")
    fun logout(@PathVariable(name = "token") token: String): Map<String, Serializable> {
        tokenSrv.revokeToken(token)
        return hashMapOf("logout" to true)
    }

    @GetMapping
    fun getUser(
        @RequestParam("access_token") token: String, principal: Principal, authentication: Authentication
    ): TBUserEntityVO {
        if (StringUtils.isBlank(principal.name)) throw TokenInvalidException("$token is invalid")
        return userSrv.getUserByUserName(principal.name)
    }

    @PostMapping("create")
    fun createUser(@RequestBody ro: CreateUserRO): TBUserEntityVO {
        return userSrv.createUser(ro)
    }
}